package com.du.config;

import java.util.Date;
import java.util.regex.Pattern;

/**
 * mysql 字段类型 对应 java 类型
 */
public enum MysqlJavaTypeMatch {

    STRING(String.class, (typeName) -> {
        return Pattern.matches(Match.STRING_PATTERN, typeName);
    }),

    DATE(Date.class, (typeName) -> {
        return Pattern.matches(Match.DATE_PATTERN, typeName);
    }),

    LONG(Long.class, (typeName) -> {
        return Pattern.matches(Match.LONG_PATTERN, typeName);
    }),

    DOUBLE(Double.class, (typeName) -> {
        return Pattern.matches(Match.DOUBLE_PATTERN, typeName);
    }),

    INTEGER(Integer.class, (typeName) -> {
        return Pattern.matches(Match.INTEGER_PATTERN, typeName);
    });

    private final Class<?> clazz;

    private final Match match;

    MysqlJavaTypeMatch(Class<?> clazz, Match match) {
        this.clazz = clazz;
        this.match = match;
    }

    /**
     * 匹配
     * @param typeName
     * @return
     */
    public static Class<?> match(String typeName) {
        if (typeName != null) {
            MysqlJavaTypeMatch[] typeMatches = MysqlJavaTypeMatch.values();
            for (MysqlJavaTypeMatch javaTypeMatch : typeMatches) {
                if (javaTypeMatch.match.isMatch(typeName)) {
                    return javaTypeMatch.clazz;
                }
            }
        }
        return null;
    }

    interface Match {
        // integer
        String INTEGER_PATTERN = "(int)|(integer)|(mediumint)|(smallint)|(tinyint)";

        String LONG_PATTERN = "(bigint)";

        String DOUBLE_PATTERN = "(decimal)|(double)|(float)";

        String STRING_PATTERN = "(varchar)|(char)|(text)|(blob)|(longtext)|(longblob)|(tinytext)|(tinyblob)";

        String DATE_PATTERN = "(datetime)|(timestamp)|(date)|(time)";

        boolean isMatch(String typeName);
    }
}
